package org.flexqueries2.utils
{
	import flash.display.DisplayObject;
	
	import mx.core.FlexGlobals;
	import mx.core.IFlexDisplayObject;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;

	public class PopupUtils
	{
		public static function createFromClass(cls:Class, closeHandler:Function = null, modal:Boolean = true):*
		{
			var ctm:IFlexDisplayObject = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, cls, modal);
			ctm.addEventListener(CloseEvent.CLOSE, onClose);
			if(closeHandler != null)
				ctm.addEventListener(CloseEvent.CLOSE, closeHandler);
			PopUpManager.centerPopUp(ctm);
			return ctm;
		}
		
		public static function createFromObject(obj:IFlexDisplayObject, closeHandler:Function = null, modal:Boolean = true):*
		{
			PopUpManager.addPopUp(obj, FlexGlobals.topLevelApplication as DisplayObject, modal);
			obj.addEventListener(CloseEvent.CLOSE, onClose);
			if(closeHandler != null)
				obj.addEventListener(CloseEvent.CLOSE, closeHandler);
			PopUpManager.centerPopUp(obj);
			return obj;
		}
				
		
		public static function remove(obj:IFlexDisplayObject):void
		{
			PopUpManager.removePopUp(obj);
		}
		
		private static function onClose(e:CloseEvent):void
		{
			remove(e.currentTarget as IFlexDisplayObject);
		}
	}
}